<template>
  <van-button
    v-if="is_followed"
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    :loading="isFollowLoading"
    @click="onFollow"
    >关注</van-button
  >
  <van-button
    v-else
    class="follow-btn"
    round
    size="small"
    @click="onFollow"
    :loading="isFollowLoading"
    >已关注</van-button
  >
</template>

<script>
import { deleteFollowAPI, addFollowAPI } from '@/api'

export default {
  // v-moodel实现组件传参且修改
  model: {
    prop: 'is_followed',
    event: 'input'
  },
  props: {
    is_followed: {
      type: Boolean,
      required: true
    },
    aut_id: {
      type: [Number, String, Object],
      required: true
    }
  },
  data () {
    return {
      isFollowLoading: false
    }
  },
  methods: {
    // 添加关注
    async onFollow () {
      // 开启按钮的 loading 状态
      this.isFollowLoading = true

      try {
        // 如果已关注，则取消关注
        const authorId = this.aut_id
        if (this.is_followed) {
          await deleteFollowAPI(authorId)
        } else {
          // 否则添加关注
          await addFollowAPI(authorId)
        }

        // 更新视图
        // this.is_followed = !this.is_followed
        // this.$emit('update-is-followed', !this.is_followed)
        this.$emit('input', !this.is_followed)
        this.$toast('操作成功')
      } catch (err) {
        // console.log(err)
        let msg = '操作失败,请稍后再试'
        if (err.response && err.response.status === 400) {
          msg = '自己不能关注自己'
        }
        this.$toast.fail(msg)
      }

      // 关闭按钮的 loading 状态
      this.isFollowLoading = false
    }
  }
}
</script>

<style scoped></style>
